//
//  ZyaPurchaseDetailController.swift
//  SlaughterClient
//
//  Created by Zhouweibin on 2018/1/29.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit

class ZyaPurchaseDetailController: UITableViewController,refreshable,DateWidgetable {

    var purchaseDetail = [ZyaPurchaseDetail]() {
        didSet {
            let moneys = purchaseDetail.map { floatTran($0.sMoneyT) }
            let amount = moneys.reduce(0) { $0 + $1 }
            bottomView.amount = String.init(format: "¥ %.2f", amount)
            
            bottomView.count = purchaseDetail.count
        }
    }
    var main = ZyaFeedOrderList(JSON:["":""])!
    
    var idkey: String?
    var isShowPrice = false
    lazy var header:ZyaPurchaseDetailHeader = {
        let v = ZyaPurchaseDetailHeader()
        return v
    }()
    
    private lazy var footer: ZyaPurchaseDetailFooter = {
        let footer = ZyaPurchaseDetailFooter.init(frame: CGRect(origin: .zero, size: CGSizeMake(KS_SCREEN_WIDTH, 40)))
        footer.addBlock = { [weak self] in
            self?.addAction()
        }
        return footer
    }()
    
    private lazy var bottomView: ZyaPurchaseDetailBottomView = {
        let view = ZyaPurchaseDetailBottomView()
        view.orderBlock = { [weak self] in
            self?.updateOrderAction()
        }
        return view
    }()
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if bottomView.superview == nil {
            bottomView.removeFromSuperview()
        }
        
        if let keyWindow = getKeyWindow(), let superV = view.superview {
            superV.addSubview(bottomView)
            bottomView.snp.makeConstraints { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(50 + keyWindow.safeAreaInsets.bottom)
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "订单详情"
        
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 90
        tableView.separatorStyle = .none
        tableView.backgroundColor = Theme.tableViewColor
        tableView.register(ZyaPurchaseDetailCell.nib, forCellReuseIdentifier: ZyaPurchaseDetailCell.identifier)
        if let keyWindow = getKeyWindow() {
            tableView.contentInset = .init(top: 0, left: 0, bottom: keyWindow.safeAreaInsets.bottom + 50, right: 0)
        }
        
//        let right1 = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(updateOrderAction))
//        let right2 = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction))
//        navigationItem.rightBarButtonItems = [right1]
        
        header.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 200)
        header.nameItem.setVal(main.tjYjrq.unwrap)
        header.nameItem.actionClosure = {
            self.showDateSelect(self) { str in
                self.main.tjYjrq = str
                self.header.nameItem.setVal(self.main.tjYjrq.unwrap)
             }
        }
        header.proItem.setVal(self.main.sClientAddress.unwrap)
        header.proItem.actionClosure = {
            var allArr = [nameAndModel<ZyaClientAddress>]()
            for item in zyareceiveAddrArr {
                let one_x = nameAndModel(shows: [item.kProvince.unwrap + item.kCity.unwrap + item.kArea.unwrap + item.clientAdd.unwrap], model: item)
                allArr.append(one_x)
            }
            let cle:(nameAndModel<ZyaClientAddress>)->() = { one in
                self.main.sClientAddress = one.model.kProvince.unwrap + one.model.kCity.unwrap + one.model.kArea.unwrap + one.model.clientAdd.unwrap
                self.header.proItem.setVal(self.main.sClientAddress.unwrap)
                
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "收货地址选择", allArr: allArr, backClosure: cle)
            self.present_FullScreen(to: vc)
            
        }
        // 修改图标
        header.proItem.assistBtn.setBackgroundImage(UIImage(named: "jt_right"), for: .normal)

        header.defaultItem.switchX.isOn = (main.advanceBs == "1")
         header.defaultItem.switchValueChangeClo = { boolx in
            self.main.advanceBs = boolx ? "1" : "0"
        }
        header.addrItem.setVal(self.main.sRemark.unwrap)
         header.addrItem.textValueChangeClo = { str in
            self.main.sRemark = str
        }
        tableView.tableHeaderView = header
        tableView.tableFooterView = footer
        
 
        KSNetwork.shared.doRequest(API.getOrdersDetail(idkey: idkey!)) { (data: BaseResult<ZyaPurchaseDetail>) in
            
            self.isShowPrice = data.showprice == 1 ? true : false
            if let info = data.info {
                self.purchaseDetail = info
            }
            self.tableView.reloadData()
        }
    }
    
    @objc func addAction() {
        let vc = ZyaFeedOrderController()
        vc.backModeArrClosure = { arr in
//
//            name.text = item.sGoodsNm
//            code.text = item.sGoodsCode
//            type.text = item.sGoodsType
//            spec.text = "规格:" +  (item.sGoodsSpec ?? "")
//            bz.text = "标包:" + (item.sGoodsBz ?? "")
//            amount.text = "确认数量:" + (item.sAmountT ?? "")
//            exeAmount.text = "已入库数量:" + (item.sExeAmount ?? "")
//            price.text = "单价:" + (item.sCessPrice ?? "")
//            money.text = "确认金额:" + (item.sMoneyT ?? "")
//
//            if !isShow {
 
            let orders = arr.map { (item) -> ZyaPurchaseDetail in
                var good = ZyaPurchaseDetail(JSON: ["s_cess_price" : ""])
            
                good?.sGoodsId = item.brandId
                good?.sGoodsNm = item.brandNm
                good?.sGoodsCode = item.brandNm
                good?.sGoodsType = item.cbTypeNm
                good?.sGoodsSpec = item.brandSpec
                good?.sGoodsBz = item.brandStand
                good?.sExeAmount = "0.0"
                good?.vouId = item.vouId
                good?.idKey = item.idKey
                good?.sAmountT = item.amount
                good?.sMoneyT = "\(doubleTran(item.amount) * doubleTran(item.brandPrice))"
                good?.sAmountZ = item.amount
                good?.sCessPrice = item.brandPrice
                return good!
                }
        
            
             self.purchaseDetail = orders
            self.tableView.reloadData()
        }
        
        vc.selectOrder = purchaseDetail
        navigationController?.pushViewController(vc, animated: true)
    }
    
     
    @objc func updateOrderAction() {
        
        let detJson = purchaseDetail.compactMap { dictionaryToJson($0.dictionaryRepresentation()) }.joined(separator: ",")
        let detddd = "[\(detJson)]"
          let mainJosn =  dictionaryToJson(main.dictionaryRepresentation())
         
        KSNetwork.shared.doRequest(API.updateOrders(main: mainJosn, detail: detddd)) { (data:BaseResult<OperateResult>) in
            if data.status == "200" {
                KSToast("修改成功")
                if let clo = self.refreshClosure {
                    clo()
                }
                self.navigationController?.popViewController(animated: true)
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
}

extension ZyaPurchaseDetailController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return purchaseDetail.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaPurchaseDetailCell.identifier) as? ZyaPurchaseDetailCell else { fatalError() }
        cell.isShow = isShowPrice
        cell.model = purchaseDetail[indexPath.row]
        cell.deleteClosure = { [indexPath] in
            guard self.purchaseDetail.count > 1 else {
                KSToast("至少留一个")
                return
            }
             alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确定", action: { _ in
                self.purchaseDetail.remove(at: indexPath.row)
                self.tableView.reloadData()
            })])
        }
        return cell
    }
    
}

